import { loadThirdTempCodeApi } from '../api';
import { useGlobalStore } from '@/service/store/global-store';
import { qsParse } from '@jecloud/utils';
/**
 * 链接
 */
export const ThirdLoginUrl = '/pages/login/third-login';
/**
 * 初始化三方登录
 * @returns
 */
export function initThirdLogin() {
  const queryStr = window.location.href.split('?')[1];
  const query = qsParse(queryStr);
  const { tempCode } = query;
  if (tempCode) {
    const globalStore = useGlobalStore();
    // 三方登录，临时授权码
    !window.location.href.includes(ThirdLoginUrl) &&
      loadThirdTempCodeApi(tempCode)
        .then((data) => {
          if (data.select) {
            uni.navigateTo({ url: `${ThirdLoginUrl}?${queryStr}` });
          } else {
            globalStore.setToken(data.token);
            doLogin();
          }
        })
        .catch(() => {
          doLogin();
        });

    return Promise.reject({ code: 'third-login' });
  } else {
    return Promise.resolve();
  }
}

function doLogin() {
  const store = useGlobalStore();
  store
    .validateToken() // 校验token
    .then(() => {
      store.login();
    })
    .catch(() => {
      store.logout();
    });
}
